<?php

namespace app\admin\model;

use MongoDB\BSON\ObjectID;
use think\Model;

class User extends Model
{
    /**
     * @var string
     */
    protected $autoWriteTimestamp = 'datetime';

    /**
     * 多对多 角色表&用户表
     * @return \think\model\relation\BelongsToMany
     */
    public function roles(){
        return $this->belongsToMany('Role');
    }

    /**
     * @return array
     */
    public function getUserRole(){
        $user = new User();
        $userRole = [];
        $ids =$user->field('user_id')->select();
       for($i=0;$i<count($ids);$i++){
           $userObject = User::get($ids[$i]->user_id);
           array_push($userRole,[
                    "key"=>$i,
                    "userName"=>$userObject->user_name,
                    "email"=>$userObject->email,
                    "role"=>$userObject->roles()->field('role_name')->value('role_name'),
                    "create_time"=>$userObject->create_time,
                    "update_time"=>$userObject->update_time
                ]
           );
       }
        return $userRole;
    }
    /**
     * @param $request
     * @return bool
     */
    public function checkLogin($request){
        $user = new User();
        $collection = $user->where('user_name',$request["userName"])->find();
        $password = md5(md5($request["password"]).$collection["salt"]);
        if($collection["password"] == $password){
            return 'success';
        }else{
            return 'error';
        }
    }

    /**
     * @param $request
     * @return string
     */
    public function checkEmail($request){
        $user = new User();
        //查看邮箱是否已被注册
        $collection = $user->where('email',$request["email"])->find();
        if(empty($collection)){
            return "success";
        }else{
            return "error";
        }
    }
    /**
     * @param $request
     * @return string
     */
    public function checkRegister($request){
        $user = new User();
        //查看邮箱是否已被注册
        $collection = $user->where('email',$request["email"])->find();
        //新增用户
        if(empty($collection)){
            //随机生成6位随机数
            $salt = rand(100000,999999);
            $password = md5(md5($request["password"]).$salt);
            $user->data([
                'user_name'=>$request['userName'],
                'email'=>$request['email'],
                'password'=>$password,
                'salt'=>$salt,
                'create_time'=>$user->createTime,
                'update_time'=>$user->updateTime
            ]);
            $user->save();
            session('loginFlag',true);
            return "success";
        }else{
            return "error";
        }
    }
}
